import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_study_2025/aes/aes_utils.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'test_http.dart';
import 'auth_provider.dart';

class LoginPage extends ConsumerWidget {
  const LoginPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final authState = ref.watch(authStateProvider);
    final authNotifier = ref.read(authStateProvider.notifier);

    return Scaffold(
      appBar: AppBar(title: const Text('登录')),
      body: Center(
        child: Column(
          children: [
            // 显示加载状态
            if (authState.isLoading)
              const CircularProgressIndicator()
            else
              ElevatedButton(
                onPressed: authState.isLoggedIn 
                    ? () => authNotifier.logout()
                    : () => authNotifier.login('123919142@qq.com', 'qwer1234'),
                child: Text(authState.isLoggedIn ? '退出登录' : '登录'),
              ),
            
            const SizedBox(height: 20),
            
            // 显示错误信息
            if (authState.error != null)
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Text(
                  '错误: ${authState.error}',
                  style: const TextStyle(color: Colors.red),
                ),
              ),
            
            // 显示用户信息
            if (authState.isLoggedIn && authState.user != null)
              Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  children: [
                    Text('已登录'),
                    Text('Token: ${authState.user?.token}'),
                    Text('Token类型: ${authState.user?.tokenType}'),
                  ],
                ),
              ),
            
            const SizedBox(height: 20),
            
            ElevatedButton(
              onPressed: () async {
                final prefs = await SharedPreferences.getInstance();
                print('token = ${prefs.getString('token')}');
              },
              child: const Text('打印token'),
            ),
            
            const SizedBox(height: 20),
            
            ElevatedButton(
              onPressed: () => authNotifier.refresh(),
              child: const Text('刷新状态'),
            ),
          ],
        ),
      ),
    );
  }
}
